<!-- 模板 -->
<template>
  <div class="browser-container">
    <!-- 导航栏 -->
    <div class="nav-bar">
      <el-icon>
        <Back :class="['back', { active: canGoBack }]" @click="goBack" />
      </el-icon>
      <el-icon>
        <Right :class="['forward', { active: canGoForward }]" @click="goForward" />
      </el-icon>
      <el-icon>
        <RefreshRight />
      </el-icon>
      <el-icon>
        <HomeFilled />
      </el-icon>
      <el-input v-model="url" style="width: 240px" placeholder="Please enter the url" @keydown.enter="go" />
      <el-icon>
        <Search @click="go" />
      </el-icon>
    </div>
    <!-- WebView 示例（可以放在这个 HTML 文件的任何地方）about:blank 或 data:text/plain -->
    <webview allowpopups ref="webview" id="webview" class="web-content" src="https://www.baidu.com/">
    </webview>

    <!-- 状态栏 -->
    <div class="status-bar">
      {{ url }}
    </div>
  </div>
</template>

<!-- 脚本 -->
<script setup>
import { ref, onMounted } from 'vue'
// import {
//   Check,
//   Delete,
//   Edit,
//   Message,
//   Search,
//   Star,
// } from '@element-plus/icons-vue'

const url = ref('https://www.baidu.com/')
const webview = ref(null)

function go() {
  webview.value.loadURL(url.value)
}
const webviewDomReady = ref(false)
const canGoBack = ref(false)
const canGoForward = ref(false)

onMounted(() => {
  const el = webview.value
  if (!el) return
  el.addEventListener('dom-ready', () => {
    webviewDomReady.value = true
    updateNavigationState()
  })
  el.addEventListener('did-start-loading', (event) => {
    updateNavigationState()
  })
  el.addEventListener('did-stop-loading', (event) => {
    updateNavigationState()
  })
  // 跳转的 URL
  el.addEventListener('did-start-navigation', (event) => {
    updateNavigationState()
    if (event.url.startsWith('http')) {
      url.value = event.url
    }
  })
})

const updateNavigationState = () => {
  if (!webview.value) return
  if (!webviewDomReady.value) return
  canGoBack.value = webview.value.canGoBack()
  canGoForward.value = webview.value.canGoForward()
}


const goBack = () => {
  const el = webview.value
  if (el.canGoBack()) el.goBack()
}

const goForward = () => {
  const el = webview.value
  if (el.canGoForward()) el.goForward()
}

</script>

<!-- 样式 -->
<style scoped>
/* 导航栏 */
.nav-bar {
  background-color: #f0f0f0;
}
/* 后退 */
.back{

}
/* 前进 */
.forward {}
/* 刷新 */
.refresh {}
/* 主页 */
.home {}
/* 地址栏 */
.url {}
/* 跳转 */
.go {}

/* 状态栏 */
.status-bar{
background-color: #f0f0f0;
}
</style>
